package com.minhua.jijiehao2.http;

import android.util.Log;

import com.minhua.jijiehao2.constants.DefineKey;
import com.minhua.jijiehao2.utils.SPUtils;
import com.minhua.jijiehao2.utils.encryption.MDUtil;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * @author moo
 * @date 2017/11/17.
 * @describe 拦截器
 */

public class BaseInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();
        Headers.Builder header = request.headers().newBuilder();
        String s = dealStr(bodyToString(request.body()));
        //Base64加密
        s = s.replaceAll(" ", "+");
        s = s.replaceAll("%2F", "/");
        s = s.replaceAll("%3D", "=");

        Log.e("Params", "http--->" + s);
        header.add(DefineKey.SIGN_MSG, sign(s));
        header.add(DefineKey.TOKEN, (String) SPUtils.get(DefineKey.TOKEN, ""));
        header.add(DefineKey.NETHEADERPARAMSKEY, "1");
        requestBuilder.headers(header.build());
        requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), s.replaceAll("\\|", "&")));
        Request build = requestBuilder.build();
        return chain.proceed(build);
    }

    /**
     * 将RequestBody转换成String
     */
    private String bodyToString(final RequestBody request) {
        try {
            final Buffer buffer = new Buffer();
            if (request != null) {
                request.writeTo(buffer);
            } else {
                return "";
            }
            return buffer.readUtf8();
        } catch (IOException e) {
            return "did not work";
        }
    }

    private String dealStr(String str) {
        if (str.contains("{")) {
            str = str.substring(1);
        }
        if (str.contains("}")) {
            str = str.substring(0, str.length() - 1);
        }
        return str.replaceAll(",", "|").replaceAll(":", "=").replaceAll("\"", "");
    }

    /**
     * 签名加密
     * mobileType=2|newPwd=2BF0C5D8E361156246E8CF2A6A65EC53|phone=18071418791|signMsg=c5485b7ae77e1b7c759a44c6e19a76be|update_channel=guanfang|vcode=5428|versionNumber=1.0.5
     * mobileType=2&newPwd=2BF0C5D8E361156246E8CF2A6A65EC53&phone=18071418791&signMsg=c5485b7ae77e1b7c759a44c6e19a76be&update_channel=guanfang&vcode=5428&versionNumber=1.0.5
     * <p>
     * mobileType=2|token=c4552beadf364b73a411e70d56caa166|update_channel=guanfang|userId=8|versionNumber=1.0.5
     */
    private String sign(String str) {
        str += "";
        return MDUtil.encode(MDUtil.TYPE.MD5, DefineKey.APP_KEY + SPUtils.get(DefineKey.TOKEN, "") + str).toUpperCase();
    }
}
